#region System
using System;
using System.Collections;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

using CStock;
using CUtil;

#endregion
using EForms;

namespace CapitalReSources
{
	/// <summary>
	/// Summary description for TreeViewStock.
	/// </summary>
    public class TreeViewStock : EForms.TreeViewStockBase, ITreeViewStock
	{

		#region Fields Private
		private IProgramContext programContext;
		private TreeNode oldSelectedNode = null;
		private IMainClass mainClass;

        protected bool customPortfolioTree;

		/// <summary>
		/// contextMenuOrigin
		/// Screen Coordinates
		/// </summary>
		private Point contextMenuOrigin;

		#endregion

		#region Constructor
		/// <summary>
		/// 
		/// </summary>
        public void InitTree(bool stockMarketType)
        {
            try
            {
                this.mainClass = MainClass.Instance;
                
                this.programContext = this.mainClass.ProgramContext;

                if (stockMarketType)
                {
                    customPortfolioTree = false;
                    this.mainClass.TreeViewStock = this;
                    //this.FillTreeFromProgramContext();
                }
                else
                {
                    customPortfolioTree = true;
                    this.mainClass.TreeViewCustomPortfolios = this;
                    
                }
                this.FillTreeFromProgramContext();
                this.programContext.HelpProvider.SetShowHelp(this, true);

                this.contextMenuOrigin = new Point(-1, -1);
            }
            catch
            {
                //this occurs in design mode - do nothing
            }



            this.AllowDrop = true;
            this.LabelEdit = true;
            this.HideSelection = false;
            this.HotTracking = true;
        }
        public TreeViewStock()
		{
			

		}
		#endregion

		#region Properties Public

     
		/// <summary>
		/// ContextMenuOrigin
		/// </summary>
		public Point ContextMenuOrigin
		{
			get
			{
				return this.contextMenuOrigin;
			}
		}

		#endregion
	
		#region ITreeViewStock

		/// <summary>
		/// 
		/// </summary>
        public void FillTreeFromProgramContext()
		{
            try
            {

                if (this.programContext.TradeEconomy != null)
                {
                    Portfolios portf = (Portfolios)this.programContext.TradeEconomy.Portfolios;
                    Debug.Assert(portf != null, "Portfolios not set");
                    if (portf == null)
                        return;

                    this.Nodes.Clear();
                    for (int i = 0; i < portf.Items.Count; i++)
                    {
                        IPortfolio port = portf[i];
                        if (this.customPortfolioTree)
                        {
                            if (! port.StockTypePortfolio)
                            {
                                if (port != null)
                                {
                                    AddPortfolioNode(port, this);
                                }

                            }

                           

                        }
                        else
                        {
                            if (port.StockTypePortfolio)
                            {
                                if (port != null)
                                {
                                    AddPortfolioNode(port, this);
                                }

                            }
                        }
                       
                       
                    }
                }
                else
                {
                    this.Nodes.Clear();
                }

            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.Assert(false, "Error filling treeview from programContext ", e.Message);
            }
		}
	
		

		
		public override void Refresh()
		{

			FillTreeFromProgramContext();
			base.Refresh();
		}
		public void Refresh(string portfolio, string share)
		{
		}

		#endregion

        public bool Select_MainNode(string strText)
        {
            for (int i = 0; i < this.Nodes.Count; i++)
            {
                TreeNode nod = this.Nodes[i];
                if (nod.Text == strText)
                {
                    this.SelectedNode = nod;
                    return true;
                    
                }
                
            }
            return false;
            
        }
        public bool Select_SubNode(string strText)
        {
            for (int i = 0; i < this.SelectedNode.Nodes.Count; i++)
            {
                TreeNode nod = this.SelectedNode.Nodes[i];
                if (nod.Text == strText)
                {
                    this.SelectedNode = nod;
                    return true;

                }

            }
            return false;

        }
        #region TreeNode Operations

        #endregion

        #region Drag
        /// <summary>
        /// 
        /// </summary>
        /// <param name="drgevent"></param>
        protected override void OnDragEnter(System.Windows.Forms.DragEventArgs drgevent)
		{
			base.OnDragEnter(drgevent);
			if ( drgevent.Data.GetDataPresent(DataFormats.Text))
			{
				drgevent.Effect = DragDropEffects.Copy;
			}
			else
			{
				drgevent.Effect = DragDropEffects.None;
			}			
			oldSelectedNode = SelectedNode;
			//System.Diagnostics.Debug.WriteLine("DragEnter["+this.GetNodeAt(drgevent.X,drgevent.Y).ToString()+"]"+" EData: "+drgevent.Data.GetData(DataFormats.Text).ToString());
		}
		#endregion

		#region private methods
		
		/// <summary>
		/// 
		/// </summary>
		/// <param name="pt"></param>
		/// <returns></returns>
		protected TreeNode FindTreeNode( System.Drawing.Point pt )
		{
			TreeNode aNode = TopNode;			
			while (aNode != null)
			{
				if (aNode.Bounds.Contains(pt))
				{
					return aNode;
				}
				aNode = aNode.NextVisibleNode;
			}

			return null;	
		}
		
		private void AddStockNode(TreeNode insertTreeNode)
		{
			int insertIndex = this.Nodes.Count;
			for (int i = 0;i < this.Nodes.Count; i++)
			{
				if (insertTreeNode.Text.CompareTo(this.Nodes[i].Text)<0)
				{
					insertIndex=i;
					break;
				}
			}
			base.Nodes.Insert(insertIndex,insertTreeNode);
		}
		

		
		#endregion

		#region TreeView Implementation
		/// <summary>
		/// 
		/// </summary>
		/// <param name="nodeName"></param>
		/// <returns></returns>
		private TreeNodeStock GetPortfolioNode(string nodeName)
		{
			TreeNodeStock portfolioNode=null;
			try
			{
				for (int i = 0; i < this.Nodes.Count ; i++)
				{
					TreeNodeStock node=(TreeNodeStock)this.Nodes[i];
				
					TreeNodeInfo locTreeNodeInfo = (TreeNodeInfo)node.Tag;
					IPortfolio locPortfolio = (IPortfolio)locTreeNodeInfo.PortfolioOrDataItem;

					//if (nodeName.Equals(node.Text))
					if (nodeName.Equals(locPortfolio.Name))
					{
						portfolioNode=node;
						break;
					}
				}
			}
			catch (Exception exc)
			{
				Debug.WriteLine("TreeViewStock - Error getting PortfolioNode: " + exc.Message);
			}
			return portfolioNode;
		}
		#endregion

		#region TreeView - Event - Keys
		/// <summary>
		/// 
		/// </summary>
		/// <param name="e"></param>
		protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs e)
		{
            	
			base.OnKeyDown(e);
//			System.Diagnostics.Debug.WriteLine("-----KeyDown MOD : " + Control.ModifierKeys.ToString() + "\n");
//			System.Diagnostics.Debug.WriteLine("-----KeyDown Data: " + e.KeyData + "\n");

            //if (e.KeyData == (Keys.C | Keys.Control) )
            //{
				
            //}
            //if (e.KeyData == (Keys.V | Keys.Control) )
            //{
				
            //}
			if (Control.ModifierKeys == Keys.Control && e.KeyData == (Keys.C | Keys.Control) )
			{
				oldSelectedNode = SelectedNode;
				System.Diagnostics.Debug.WriteLine("Control - C pressed for node " + oldSelectedNode.Text);
				
			}
			if (Control.ModifierKeys == Keys.Control && e.KeyData == (Keys.V | Keys.Control) )
			{
				//try to copy share nodes in portfolio nodes
				System.Diagnostics.Debug.WriteLine("Control - V pressed for node " + this.SelectedNode.Text);
				TreeNodeStock copyNode = this.oldSelectedNode as TreeNodeStock;
				TreeNodeStock pasteNode = this.SelectedNode as TreeNodeStock;
				if(copyNode != null && pasteNode != null)
				{
					CopyPasteProcedure(copyNode, pasteNode);
				}
			}
			Keys keyData=e.KeyData;
//			if (e.Control){System.Diagnostics.Debug.WriteLine("If-Key-Control-Down = "+keyData.ToString());}
			switch (keyData)
			{
					
                //case Keys.C:
                //{
                //    //System.Diagnostics.Debug.WriteLine("Key-C-Down = "+keyData.ToString());
                //    break;
                //}
                //case Keys.V:
                //{
                //    //System.Diagnostics.Debug.WriteLine("Key-V-Down = "+keyData.ToString());
                //    break;
                //}
                //case  Keys.Delete:
                //{
                //    break;

					
                //}
				default:
				{
					if ((keyData==Keys.C))
					{
						System.Diagnostics.Debug.WriteLine("Default-Ctrl-C");
						Clipboard.SetDataObject(oldSelectedNode,true);
					}
					//Debug.Assert(false,"Key undefined or not used - "+keyData.ToString());
					break;
				}
			}
		}
		private void CopyPasteProcedure(TreeNodeStock copyNode, TreeNodeStock pasteNode)
		{

			//Portfolio
			Portfolio targetPortfolio=(Portfolio)pasteNode.PortfolioOrDataItem;
			//Share
			DataItem copyShare = (DataItem)((DataItem)copyNode.PortfolioOrDataItem).Clone();
			
			//set buy date to current date
			copyShare.BuyDate = this.programContext.Configuration.Dates.DateMax;


			//Portfolio
			targetPortfolio.DataItems.Add(copyShare,targetPortfolio);
			targetPortfolio.Serialize();
			TreeViewStockBase.FillPortfolioNode(pasteNode, targetPortfolio);

		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="e"></param>
		protected override void OnKeyUp(System.Windows.Forms.KeyEventArgs e)
		{
			base.OnKeyUp(e);
            Keys keyData = e.KeyData;
			if ( (keyData == Keys.C) && e.Control)
			{
				//System.Diagnostics.Debug.WriteLine("XXX If-Key-Control-Up = "+keyData.ToString());
				MessageBox.Show("Control clicked");
			}
		
			switch (keyData) 
			{
               
				case Keys.C:
				{
                    //System.Diagnostics.Debug.WriteLine("Key-C-Up = "+keyData.ToString()+
                    //    "Modifiers="+e.Modifiers.ToString());
					if (e.Control)
					{
						TreeNodeStock copyTreeNode= (TreeNodeStock) this.SelectedNode;
						//System.Diagnostics.Debug.WriteLine("SelectedNode = "+copyTreeNode);
					}
                    //else
                    //{System.Diagnostics.Debug.WriteLine("KeyEvent-Up = "+e.ToString());}
                    break;
				}
				case Keys.V:
				{
					//System.Diagnostics.Debug.WriteLine("Key-V-Up = "+keyData.ToString());
					break;
				}
				case  Keys.Delete:
				{
					TreeNodeStock deleteNode=(TreeNodeStock)this.SelectedNode;
					if (this.DeleteCondition(deleteNode))
					{
						DeleteProcedure(deleteNode);
					}
					break;
				}
                //case Keys.Insert:
                //{
                //    string portfolioName = "NewPortfolio"+(System.Environment.TickCount);
                //    IPortfolio insertPortfolio = this.programContext.TradeEconomy.Portfolio_GetOrCreate(portfolioName);
                //    insertPortfolio.ID = portfolioName;
                //    insertPortfolio.Serialize();
                //    this.FillTreeFromProgramContext();
                //    break;
                //}
				default:
				{
					System.Diagnostics.Debug.WriteLine("Key-Default-Up = "+keyData.ToString());
					//Debug.Assert(false,"Key undefined or not used - "+keyData.ToString());
					break;
				}
			}
		}
		#endregion

		#region Event MouseUp
		
		/// <summary>
		/// 
		/// </summary>
		/// <param name="e"></param>
		protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs e)
		{
            this.mainClass.CustomPortfolioTreeViewActive = this.customPortfolioTree;
			base.OnMouseUp(e);
            //this.programContext.Logfile.WriteTimeSpanLog("   -> Tree View - OnMouseUp");
			if(e.Button == System.Windows.Forms.MouseButtons.Right)
			{
				Point treeNodePointTreeView = new Point(e.X,e.Y);
				Point treeNodePointScreen = this.PointToScreen(treeNodePointTreeView);
				this.contextMenuOrigin = treeNodePointScreen;
				try
				{
                    TreeNode tn = this.GetNodeAt(treeNodePointTreeView) ;
                    

                    if (tn != null)
                    {
                        this.SelectedNode = tn;
                        TreeNodeStock mySelectedNode = tn as TreeNodeStock;
                        //SetSelection(mySelectedNode);

                        
                        //Debug.WriteLine("ContextNode: " + treeViewNode.ToString());
                        if (this.mainClass.View.ContextMenuTreeView != null)
                            this.mainClass.View.ContextMenuTreeView.Show(this, treeNodePointTreeView);
                    }
                }
				catch(Exception exc)
				{
					Debug.Assert(false,"Error at click : " + exc.Message);
				}
			}
			else
			{
				//this.WriteLine("TreeView-OnMouseUp(): "," Not Button Right");	
			}
		}
		#endregion

		#region TreeView - Delete
		/// <summary>
		/// 
		/// </summary>
		/// <param name="deleteNode"></param>
		/// <returns></returns>
		private bool DeleteCondition(TreeNodeStock deleteNode)
		{
            this.mainClass.CustomPortfolioTreeViewActive = this.customPortfolioTree;
			switch (deleteNode.TreeNodeBase)
			{
				case TreeNodeInfo.PORTFOLIO:
				{
					
					IPortfolio Portfolio_Delete = (Portfolio)deleteNode.PortfolioOrDataItem;
					if(Portfolio_Delete.WriteProtect)
						return false;

					return true;
	
				}
				case TreeNodeInfo.SHARE:
				{
					IPortfolio Portfolio_Delete=(Portfolio)deleteNode.PortfolioTreeNode.PortfolioOrDataItem;
					if(Portfolio_Delete.WriteProtect)
						return false;

					IDataItem dci =(DataItem)deleteNode.PortfolioOrDataItem;

					if(dci.Number > 0)
					{
						dci.Number = 0;
						return true;
					}
					else
					{
						return true;
					}

				}
				case TreeNodeInfo.PARAMETER:
				{
					// No Implementation -> Don't remove ParameterNodes
					return false;
				}
				default:
				{
					Debug.Assert(false,"TreeView-DeleteCondition()","Error due to unknown Node Type");
					return false;
				}
			}
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="deleteNode"></param>
		private void DeleteProcedure(TreeNodeStock deleteNode)
		{
            if (!EForms.DialogUtils.ShowDeleteBox(deleteNode.Text))
                return;

            try
            {
                //ITreeNodeInfo deleteNodeInfo=deleteNode.TreeNodeInfo();
                switch (deleteNode.TreeNodeBase)
                {
                    case TreeNodeInfo.PORTFOLIO:
                        {
                            Portfolio Portfolio_Delete = (Portfolio) deleteNode.PortfolioOrDataItem;

                            if (Portfolio_Delete.WriteProtect)
                            {
                                System.Windows.Forms.MessageBox.Show("This Portfolio is write protected and cannot be changed or deleted " +
                                    "and cannot be deleted");
                            }
                            else
                            {
                                System.Diagnostics.Debug.WriteLine("TreeViewStock-DeleteProcedure()-Portfolio: " + Portfolio_Delete.Name + " deleted");
                                this.programContext.TradeEconomy.Portfolio_Delete(Portfolio_Delete);
                                FillTreeFromProgramContext();
                            }
                            break;
                        }
                    case TreeNodeInfo.SHARE:
                        {
                            DataItem deleteShare = (DataItem)deleteNode.PortfolioOrDataItem;
                            Portfolio parentPortfolio = (Portfolio) deleteNode.PortfolioTreeNode.PortfolioOrDataItem;
                            IDataClass dc = deleteShare.DataClass;

                           
                            if (!dc.Delete())
                            {
                              //delete might fail and we might change the implementation so that something else is done ...

                            }
                            parentPortfolio.DataItems.Remove(deleteShare);
                            parentPortfolio.Serialize();
                            FillPortfolioNode(GetPortfolioNode(parentPortfolio.Name), parentPortfolio);
                            System.Diagnostics.Debug.WriteLine("TreeViewStock-DeleteProcedure()-Share: " + deleteShare.ToString() + " deleted");

                            break;
                        }
                    case TreeNodeInfo.PARAMETER:
                        {
                            // No Implementation -> Don't remove ParameterNodes
                            break;
                        }
                    default:
                        {
                            Debug.Assert(false, "TreeViewStock-DeleteProcedure()", "Error due to unknown Node Type");
                            break;
                        }
                }
            }
            catch(Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Error deleting entry: " + ex.Message);
            }
		}
		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public bool DeleteSelectedNode()
		{
            this.mainClass.CustomPortfolioTreeViewActive = this.customPortfolioTree;
			try
			{
				TreeNodeStock tns = this.SelectedNode as TreeNodeStock ;
				Debug.Assert(tns != null);
				if(tns != null)
					this.DeleteProcedure(tns);
				return true;
			}
			catch(Exception e)
			{
				Debug.WriteLine("Error deleting",e.Message);
				return false;
			}
		}

		#endregion

		#region TreeView - Event - ItemDrag
		/// <summary>
		/// 
		/// </summary>
		/// <param name="e"></param>
		protected override void OnItemDrag(System.Windows.Forms.ItemDragEventArgs e)
		{
			
			base.OnItemDrag(e);
            this.mainClass.CustomPortfolioTreeViewActive = this.customPortfolioTree;
            TreeNodeStock itemDragNode = (TreeNodeStock)e.Item;
			System.Diagnostics.Debug.WriteLine("TreeViewStock-OnItemDrag["+itemDragNode.Text+"]");
			try
			{
				if (ItemDragCondition(itemDragNode))
				{
					this.ItemDragProcedure(itemDragNode,DragDropEffects.Copy);
				}
				else
				{
					this.ItemDragProcedure(itemDragNode,DragDropEffects.None);
				}	
			}
			catch (Exception exc)
			{
				Debug.WriteLine("TreeViewStock - Error in OnItemDrag: " + exc.Message);
			}
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="itemDragNode"></param>
		/// <returns></returns>
		private bool ItemDragCondition(TreeNodeStock itemDragNode)
		{
            this.mainClass.CustomPortfolioTreeViewActive = this.customPortfolioTree;
			switch (itemDragNode.TreeNodeBase)
			{
				case TreeNodeInfo.PORTFOLIO:
				case TreeNodeInfo.PARAMETER:
				{
					return false;
				}
				case TreeNodeInfo.SHARE:
				{
					//Only from Default Portfolio
					Portfolio itemDragPortfolio=(Portfolio)itemDragNode.PortfolioTreeNode.PortfolioOrDataItem;
					if (itemDragPortfolio.Name.Equals(Portfolio.defaultPortfolioName))
					{
						// Only Shares from DefaultPortfolio can be dragged 
						return true;
					}
					else 
					{
						// *** 200212 Excluded
						// return false;
						return true;
					}
				}
				default:
				{
					throw new Exception("TreeViewStock-ItemDragCondition()-UnknownNodeType");
				}
			}
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="itemDragNode"></param>
		/// <param name="dragDropEffects"></param>
		private void ItemDragProcedure(TreeNodeStock itemDragNode,DragDropEffects dragDropEffects)
		{
			DoDragDrop(itemDragNode,dragDropEffects);
		}
		#endregion

		#region TreeView - Event - DragOver
		/// <summary>
		/// 
		/// </summary>
		/// <param name="drgevent"></param>
		protected override void OnDragOver(System.Windows.Forms.DragEventArgs drgevent)
		{
            this.mainClass.CustomPortfolioTreeViewActive = this.customPortfolioTree;
			base.OnDragOver(drgevent);
			if (drgevent.Data.GetDataPresent(DataFormats.Serializable))
			{
				Point dragOverPoint = this.PointToClient(new Point(drgevent.X,drgevent.Y));
				TreeNodeStock dragOverNode=(TreeNodeStock)this.GetNodeAt(dragOverPoint.X,dragOverPoint.Y);
				System.Diagnostics.Debug.WriteLine
					("TreeViewStock-OnDragOver()"
					+" Node: "+dragOverNode.Text
					+" Type: "+dragOverNode.TreeNodeBase
					+" Parent: "+((Portfolio)dragOverNode.PortfolioTreeNode.PortfolioOrDataItem).Name
					);
				if (DragOverCondition(dragOverNode))
				{
					drgevent.Effect = DragDropEffects.Copy;
					DragOverProcedure(dragOverNode,DragDropEffects.Copy);
				}
				else
				{
					drgevent.Effect=DragDropEffects.None;
				}
			}
			else
			{
				drgevent.Effect=DragDropEffects.None;
			}
		}	
		/// <summary>
		/// 
		/// </summary>
		/// <param name="dragOverTreeNode"></param>
		/// <returns></returns>
		private bool DragOverCondition(TreeNodeStock dragOverTreeNode)
		{
			return true;
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="dragOverNode"></param>
		/// <param name="dragDropEffekts"></param>
		private void DragOverProcedure(TreeNodeStock dragOverNode,DragDropEffects dragDropEffekts)
		{
			//Nothing special to do
		}
		#endregion

		#region TreeView - Event - DragDrop
		/// <summary>
		/// 
		/// </summary>
		/// <param name="drgevent"></param>
		protected override void OnDragDrop(System.Windows.Forms.DragEventArgs drgevent)
		{
            this.mainClass.CustomPortfolioTreeViewActive = this.customPortfolioTree;
			base.OnDragDrop(drgevent);
			System.Diagnostics.Debug.WriteLine("TreeViewStock-OnDragDrop()");
			try
			{
				if (drgevent.Data.GetDataPresent(DataFormats.Serializable))
				{
					drgevent.Effect=DragDropEffects.Copy;
					//TargetNode
					Point treeViewPoint = this.PointToClient(new Point(drgevent.X,drgevent.Y));
					TreeNodeStock targetNode = (TreeNodeStock)this.GetNodeAt(treeViewPoint.X,treeViewPoint.Y);
					//DragDropNode
					object dragDropObject = drgevent.Data.GetData(typeof(TreeNodeStock));
					TreeNodeStock dragDropNode=(TreeNodeStock)dragDropObject;
					if (DragDropCondition(targetNode,dragDropNode))
					{
						DragDropProcedure(targetNode,dragDropNode);
					}
					else
					{
						drgevent.Effect=DragDropEffects.None;
					}
				}
				else
				{
					drgevent.Effect=DragDropEffects.None;
				}
			}
			catch (Exception exc)
			{
				Debug.Assert(false,"TreeViewStock-OnDragDrop() - Exception: " + exc.Message);
			}
			this.mainClass.Print();
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="targetNode"></param>
		/// <param name="dragDropNode"></param>
		/// <returns></returns>
		private bool DragDropCondition(TreeNodeStock targetNode,TreeNodeStock dragDropNode)
		{
			try
			{
				switch (targetNode.TreeNodeBase)
				{
					case TreeNodeInfo.PORTFOLIO:
					{
						// Node can only be dropped 
						// if Target Portfolio does not already ShareNode
						if (!targetNode.Nodes.Contains(dragDropNode))
						{
							return true;
						}
						else
						{
							return false;
						}
					}
					case TreeNodeInfo.SHARE:
					case TreeNodeInfo.PARAMETER:
					{
						return false;
					}
					default:
					{
						throw new Exception("TreeViewStock-DragDropCondition()-Unknown NodeType");
					}
				}
			}
			catch (NullReferenceException exc)
			{
				Debug.Assert(false,"TreeViewStock-DragDropCondition()","targetNode==null or dragDropNode==null"+exc.Message);
				return false;
			}
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="targetNode"></param>
		/// <param name="dragDropNode"></param>
		private void DragDropProcedure(TreeNodeStock targetNode , TreeNodeStock dragDropNode)
		{
			try
			{
				//Portfolio
				Portfolio targetPortfolio = (Portfolio)targetNode.PortfolioOrDataItem;
				//Share
				DataItem dragDropShare = (DataItem)((DataItem)dragDropNode.PortfolioOrDataItem).Clone();
				//Portfolio				
				targetPortfolio.DataItems.Add(dragDropShare,targetPortfolio);
				// *** 200212 Excluded
				targetPortfolio.Serialize();
				FillPortfolioNode(targetNode,targetPortfolio);
			}
			catch (Exception exc)
			{
				Debug.WriteLine("TreeViewStock - DragDropProcedure: " + this.ToString(),exc.Message);
				Debug.Assert(false,"TreeViewStock-DragDropProcedure()","targetNode==null or dragDropNode==null"+exc.Message);
			
			}
			
		}
		#endregion

      
		#region TreeView - Event - After Select
		/// <summary>
		/// 
		/// </summary>
		/// <param name="e"></param>
        private bool SetSelection(TreeNodeStock mySelectedNode)
        {
            this.mainClass.CustomPortfolioTreeViewActive = this.customPortfolioTree;
            switch (mySelectedNode.TreeNodeBase)
            {
                case TreeNodeInfo.PORTFOLIO:
                    {
                        //this.programContext.Logfile.WriteTimeSpanLog("   -> Tree View - OnAfterSelect");

                        //Portfolio_Selected sets also Portfolio_Simulation
                        this.programContext.TradeEconomy.Portfolio_Selected = (Portfolio)mySelectedNode.PortfolioOrDataItem;
                        if (this.programContext.TradeEconomy.Portfolio_Selected != null && this.programContext.TradeEconomy.Portfolio_Selected.DataItems != null &&
                            this.programContext.TradeEconomy.Portfolio_Selected.DataItems.Count > 0)
                        {
                            this.programContext.TradeEconomy.Portfolio_Selected.DataItem_Selected = this.programContext.TradeEconomy.Portfolio_Selected.DataItems[0] as IDataItem;
                            
                        }


                        //Note !!!
                        //the next statement implies calling Portfolio.Value_Total by setting the portfolio in the grid
                        //means calculating the Portfolio value. 
                        //---This will calculate all share current values
                        // which implies the reading of all share data !
                        this.mainClass.DoTreeMenuMenuPortfolioShowInGrid();
                        this.mainClass.PropertyGrid.SelectedObject = this.programContext.TradeEconomy.Portfolio_Selected;
                        //this.mainClass.ShowFundamentalDataInGrid();
                        break;
                    }
                case TreeNodeInfo.SHARE:
                    {
                        //request parent portfolio:

                        TreeNodeStock parentNode = mySelectedNode.Parent as TreeNodeStock;
                        if (parentNode != null)
                        {
                            //parentNode.TreeNodeBase
                            //ShareNode
                            DataItem mySelectedItem = (DataItem)mySelectedNode.PortfolioOrDataItem;
                            this.mainClass.PropertyGrid.SelectedObject = mySelectedItem;

                            //PortfolioNode (Select also corresponding Portfolio)
                            TreeNodeStock portfolioNode = (TreeNodeStock)mySelectedNode.PortfolioTreeNode;
                            this.programContext.TradeEconomy.Portfolio_Selected = (Portfolio)portfolioNode.PortfolioOrDataItem;
                            this.programContext.TradeEconomy.Portfolio_Selected.DataItem_Selected = mySelectedItem;
                            this.mainClass.ShowFundamentalDataInGrid();

                        }
                        break;
                    }
                case TreeNodeInfo.PARAMETER:
                    {
                        //System.Diagnostics.Debug.WriteLine("TreeViewStock-OnAfterSelect -Parameter selected");
                        break;
                    }
                default:
                    {
                        //no tree node info set
                        //Debug.Assert(false,"TreeViewStock-OnAfterSelect -Unknown TreeNodeInfo");
                        break;
                        //throw new Exception("TreeViewStock-OnAfterSelect()-Unknown TreeNodeInfo");
                    }
            }
            return true;

        }
        protected override void OnAfterSelect(System.Windows.Forms.TreeViewEventArgs e)
		{
            this.mainClass.CustomPortfolioTreeViewActive = this.customPortfolioTree;

			MainClass.Instance.View.Cursor =  System.Windows.Forms.Cursors.WaitCursor;
			base.OnAfterSelect(e);
		
			
			try
			{
				TreeNodeStock mySelection = (TreeNodeStock)e.Node;
                SetSelection(mySelection);

				
			}
			catch(Exception exc)
			{
				System.Diagnostics.Debug.Assert(false,"Error selecting node " + exc.Message);
			}
			MainClass.Instance.View.Cursor =  System.Windows.Forms.Cursors.Default;
		}
		#endregion

		#region TreeView Labeledit
		/// <summary>
		/// 
		/// </summary>
		/// <param name="e"></param>
		protected void OnAfterLabelEditOld(System.Windows.Forms.NodeLabelEditEventArgs e)
		{
			if (e.Label != null)
			{
				if(e.Label.Length > 0)
				{
					if (e.Label.IndexOfAny(new char[]{'@', '.', ',', '!'}) == -1)
					{
						//Stop editing without canceling the label change.
						if (!this.programContext.TradeEconomy.ContainPortfolio(e.Label))
						{
							e.Node.EndEdit(false);
							TreeNodeStock editTreeNode = (TreeNodeStock)e.Node;
							TreeNodeInfo editNodeInfo = ((TreeNodeInfo)editTreeNode.Tag);
							if (editNodeInfo.BaseType == TreeNodeInfo.PORTFOLIO)
							{
								CStock.Portfolio editPortfolio = ((Portfolio)editNodeInfo.PortfolioOrDataItem);
								string oldName = editPortfolio.Name;
								if(editPortfolio.WriteProtect)
								{
									editPortfolio.Name = oldName;
									e.CancelEdit = true;
								}
								else
								{

									
									string oldFileName = ((IPortfolio)(editPortfolio)).FileName;

									editPortfolio.Name = e.Label;
									if(editPortfolio.Serialize())
									{
                                        this.programContext.TradeEconomy.Portfolios.Items.Remove(editPortfolio);
										File.Delete(this.programContext.Configuration.Directories.PortfolioPath + "\\" + oldFileName);
                                        this.programContext.TradeEconomy.Portfolios.Items.Add(editPortfolio);
										editPortfolio.RenamePortfolioDirectory(oldName,editPortfolio.Name,this.programContext.Configuration.Directories.QuotesDataPath);

									}
									else
									{
										//undo action:
										editPortfolio.Name = oldName;
										e.CancelEdit = true;
										//									this.SelectedNode.Text = oldName;
										//									e.Node.BeginEdit();
									
									}
								}
							}
						}
						else
						{
							/* Cancel the label edit action, inform the user, and 
						   place the node in edit mode again. */
							e.CancelEdit = true;
							MessageBox.Show("Existing LabelName" + "","Node Label Edit");
							e.Node.BeginEdit();
						}
					}
					else
					{
						/* Cancel the label edit action, inform the user, and 
						   place the node in edit mode again. */
						e.CancelEdit = true;
						MessageBox.Show("Invalid tree node label.\n" + "The invalid characters are: '@','.', ',', '!'", 
							"Node Label Edit");
						e.Node.BeginEdit();
					}
				}
				else
				{
					/* Cancel the label edit action, inform the user, and 
					   place the node in edit mode again. */
					e.CancelEdit = true;
					MessageBox.Show("Invalid tree node label.\nThe label cannot be blank","Node Label Edit");
					e.Node.BeginEdit();
				}	
			}
			base.OnAfterLabelEdit(e);
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="e"></param>
		protected override void OnBeforeLabelEdit(System.Windows.Forms.NodeLabelEditEventArgs e)
		{
            this.mainClass.CustomPortfolioTreeViewActive = this.customPortfolioTree;
			base.OnBeforeLabelEdit(e);
			TreeNodeStock editTreeNode = (TreeNodeStock)e.Node;
			switch (editTreeNode.TreeNodeBase)
			{
				default:
				case TreeNodeInfo.PARAMETER:
				case TreeNodeInfo.SHARE:
				{
					e.Node.EndEdit(true);
					break;
				}
				case TreeNodeInfo.PORTFOLIO:
				{
					if (editTreeNode.Text.Equals(Portfolio.defaultPortfolioName))
					{
						e.Node.EndEdit(true);
					}
					break;
				}
			}
		}
		public void BeginEditNode()
		{
			this.SelectedNode.BeginEdit();
		}

		#endregion

	
		protected override void OnAfterCollapse(TreeViewEventArgs e)
		{
            this.mainClass.CustomPortfolioTreeViewActive = this.customPortfolioTree;
			MainClass.Instance.View.Cursor =  System.Windows.Forms.Cursors.WaitCursor;

			this.SelectedNode = e.Node;
			// TODO:  Add TreeViewStock.OnAfterCollapse implementation
			base.OnAfterCollapse (e);
			TreeNodeStock tns = this.SelectedNode as TreeNodeStock;
			switch (tns.TreeNodeInfo.BaseType)
			{
				case TreeNodeInfo.PORTFOLIO:
				{
					tns.ImageIndex = 0;
					tns.SelectedImageIndex = 0;
					break;
					
					
				}
				case TreeNodeInfo.SHARE:
				{
					tns.ImageIndex = 2;
					tns.SelectedImageIndex = 2;
					break;

				}
				case TreeNodeInfo.PARAMETER:
				{
					break;
				}
				default:
				{
					Debug.Assert(false,"TreeView-after select() + Error due to unknown Node Type");
					break;
					
				}
			}
			MainClass.Instance.View.Cursor =  System.Windows.Forms.Cursors.Default;
		}
	
		protected override void OnAfterExpand(TreeViewEventArgs e)
		{
            this.mainClass.CustomPortfolioTreeViewActive = this.customPortfolioTree;
			MainClass.Instance.View.Cursor =  System.Windows.Forms.Cursors.WaitCursor;
			// TODO:  Add TreeViewStock.OnAfterExpand implementation
			this.SelectedNode = e.Node;
			base.OnAfterExpand (e);
			TreeNodeStock tns = this.SelectedNode as TreeNodeStock;
			//string str = tns.TreeNodeInfo.BaseType;
			switch (tns.TreeNodeInfo.BaseType)
			{
				case TreeNodeInfo.PORTFOLIO:
				{
					tns.ImageIndex = 1;
					tns.SelectedImageIndex = 1;
					break;
					
					
				}
				case TreeNodeInfo.SHARE:
				{
					tns.ImageIndex = 3;
					tns.SelectedImageIndex = 3;
					break;
				}
				case TreeNodeInfo.PARAMETER:
				{
					break;
				}
				default:
				{
					Debug.Assert(false,"TreeView-after select() + Error due to unknown Node Type");
					break;
				}
			}
			MainClass.Instance.View.Cursor =  System.Windows.Forms.Cursors.Default;
			

		}
	}
}
